package com.akuhome.resource.service.entity;

import com.akuhome.resource.dao.BuildDao;
import com.akuhome.resource.dao.DormitoryDao;
import com.akuhome.resource.dto.BuildInfo;
import com.akuhome.resource.entity.Build;
import com.akuhome.resource.enums.ResultEnum;
import com.akuhome.resource.exception.ResourceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BuildService {
    @Autowired
    private BuildDao buildDao;
    @Autowired
    private DormitoryService dormitoryService;

    public List<Build> findAllBuild(){
        return buildDao.findAllBuild();
    }

    public List<BuildInfo> findAllBuildInfo(){
        return buildDao.findAllBuildInfo();
    }

    public Integer insertBuild(Build build){
        Integer row = buildDao.insertBuild(build);
        if(row == 1){
            return build.getId();
        }else{
            throw new ResourceException(ResultEnum.ARG_MISMATCH_ERROR);
        }
    }

    public Object updateBuild(Build build){
        Integer row = buildDao.updateBuild(build);
        if(row == 1){
            return null;
        }else if(row == 0){
            throw new ResourceException(ResultEnum.ARG_MISMATCH_ERROR);
        }else{
            throw new ResourceException(ResultEnum.UNKNOWN_ERROR);
        }
    }

    public Object deleteBuild(Integer buildId){
        Integer row = buildDao.deleteBuildById(buildId);
        if(row == 1){
            return null;
        }else{
            throw new ResourceException(ResultEnum.ARG_MISMATCH_ERROR);
        }
    }
    @Transactional
    public void insertBuildInfo(BuildInfo buildInfo){
        Integer row = buildDao.insertBuild(buildInfo.getBuild());
        dormitoryService.insertDormitoryList(buildInfo.getDormitory(),buildInfo.getBuild().getId());
    }
    @Transactional
    public void updateBuildInfo(BuildInfo buildInfo){
        buildDao.updateBuild(buildInfo.getBuild());
        dormitoryService.updateDormitoryList(buildInfo.getDormitory());
    }
    @Transactional
    public void deleteBuildInfo(Integer buildId){
        dormitoryService.deleteDormitoryByBuildId(buildId);
        buildDao.deleteBuildById(buildId);
    }
}
